{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Two-Sum\n",
    "\n",
    "[The Original Question](https://mp.weixin.qq.com/s/7FiOQoMiPNkABF97wnBBXg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "You are given a list of numbers, and a target number `k`. Return whether or not there are two numbers in the list that add up to `k`.\n",
    "\n",
    "Try to do it in a single pass of the list."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example\n",
    "\n",
    "```python3\n",
    "array = [4, 7, 1 , -3, 2]\n",
    "target = 5\n",
    "\n",
    "return True\n",
    "```\n",
    "\n",
    "$$\n",
    "4 + 1 = 5\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def check_sum(array: list, target: int) -> bool:\n",
    "    \n",
    "    # Sort the list in ascending way.\n",
    "    array.sort()\n",
    "    \n",
    "    # Tag the 2 items.\n",
    "    start = 0\n",
    "    end = len(array) - 1\n",
    "    \n",
    "    # Check until no item pair satisfy the requirement.\n",
    "    while start < end:\n",
    "        if array[start] + array[end] > target:\n",
    "            \n",
    "            # Decrease the large item.\n",
    "            end -= 1\n",
    "        elif array[start] + array[end] < target:\n",
    "            \n",
    "            # Increase the small item.\n",
    "            start += 1\n",
    "        else:\n",
    "            \n",
    "            # Target item pair found\n",
    "            return True\n",
    "        \n",
    "    # No satisfaction.\n",
    "    return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "print(check_sum([4, 7, 1, -3, 2], 5))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
